'use strict';
var qr = require('qr-image');
const Service = require('egg').Service;
var md5 = require('md5');
let svgCaptcha = require('svg-captcha')

class UtlisService extends Service {
    async captcha() {
        const captcha = svgCaptcha.create({
            size: 4, //验证码长度
            fontSize: 45, //验证码字号
            noise: 1, //干扰线条数目
            width: 120, //宽度
            height: 32, //高度
            color: true, //验证码字符是否有颜色，默认是没有，但是如果设置了背景颜色，那么默认就是有字符颜色
            background: '#ccc' //beijing
        })

        return captcha
    }

    async md5(data) {
        return md5(data)
    }

    async getDate() {
        return new Date().getTime() / 1000
    }

    async authAdmin() {
        //  1、获取当前用户的角色和isSuper
        let roleId = this.ctx.session.userinfo.role_id;
        let isSuper = this.ctx.session.userinfo.is_super;
        let adminPath = this.config.pathname;
        let pathname = this.ctx.request.url;   //当前访问的地址
        pathname = pathname.split("?")[0];

        //忽略权限判断的地址
        if (this.config.ignoreUrl.indexOf(pathname) != -1 || isSuper == 1) {
            return true;
        }

        // // 2、查询当前角色拥有的权限（查询当前角色的权限id） 把查找到的数据放在数组中
        // let roleAccessArr = [];
        // let roleAuthResult = await this.ctx.model.RoleAccess.findAll({
        //     where: {
        //         roleId: roleId
        //     }
        // });
        // for (let i = 0; i < roleAuthResult.length; i++) {
        //     roleAccessArr.push(roleAuthResult[i].accessId);
        // }
        let resultRole = await this.app.mysql.query('select access.id,url from role_access left join access on role_access.access_id = access.id where role_id =? and module_id != 0', [roleId])

        let roleAccessArr = [];
        for (let i = 0; i < resultRole.length; i++) {
            roleAccessArr.push(resultRole[i].id)
        }
        console.log(roleAccessArr)

        // 3、获取当前访问的url 对应的权限id
        let accessUrl = pathname.replace(`/${adminPath}/`, "");

        let accUrl = await this.app.mysql.query('select id from access where url = ?', [accessUrl])
        console.log(accUrl, '===')
        // 4、判断当前访问的url对应的权限id 是否在权限列表中的id中
        if (accUrl.length > 0) {
            if (roleAccessArr.indexOf(accUrl[0].id) != -1) {
                return true;
            }
            return false;
        }
        return false;


    }

    async createSvg() {
        var qr_svg = qr.image('https://blog.dbsgw.com/sort/19', { type: 'png' });
        let result = await this.service.admin.upload.uploadCos(qr_svg,'.png')
        return result
    }
}

module.exports = UtlisService;
